package com.lgy.controller;

import com.lgy.beans.ProductCategory;
import com.lgy.beans.ProductInfo;
import com.lgy.dto.CartDTO;
import com.lgy.product.common.DecreaseStockInput;
import com.lgy.service.CategoryService;
import com.lgy.service.ProductService;
import com.lgy.vo.ProductInfoVO;
import com.lgy.vo.ProductVO;
import com.lgy.vo.ResultVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.lgy.utils.ResultVOUtil.success;

/**
 * 商品
 */
@RestController
@RequestMapping("product")
public class ProductController {

    @Autowired
    private ProductService productService;

    @Autowired
    private CategoryService categoryService;

    /**
     * 1. 查询所有在架的商品
     * 2. 获取类目type列表
     * 3. 查询类目
     * 4. 构造数据
     */
    @GetMapping("/list")
    public ResultVO<ProductVO> list() {
        List<ProductInfo> productInfoList = productService.findUpAll();
        List<ProductCategory> productCategoryList = categoryService.findByCategoryTypeIn(
                productInfoList.stream().map(ProductInfo::getCategoryType).collect(Collectors.toList()));
        List<ProductVO> productVOList = new ArrayList<>();
        productCategoryList.forEach(productCategory -> {
            ProductVO productVO = new ProductVO();
            productVO.setCategoryName(productCategory.getCategoryName());
            productVO.setCategoryType(productCategory.getCategoryType());
            List<ProductInfoVO> productInfoVOList = new ArrayList<>();
            productInfoList.stream().filter(productInfo -> productInfo.getCategoryType()
                    .equals(productCategory.getCategoryType())).forEach(productInfo -> {
                        ProductInfoVO productInfoVO = new ProductInfoVO();
                        BeanUtils.copyProperties(productInfo, productInfoVO);
                        productInfoVOList.add(productInfoVO);
            });
            productVO.setProductInfoVOList(productInfoVOList);
            productVOList.add(productVO);
        });

        return success(productVOList);
    }

    /**
     * 获取商品列表(给订单服务调用)
     * @param productIdList
     * @return
     */
    @PostMapping("/listForOrder")
    public List<ProductInfo> listForOrder(@RequestBody List<String> productIdList) {
        return productService.findList(productIdList);
    }

    @PostMapping("/decreaseStock")
    public void decreaseStock(@RequestBody List<DecreaseStockInput> decreaseStockInputList) {
        productService.decreaseStock(decreaseStockInputList);
    }
}
